<?php

class Menu extends AppModel {

    var $name = 'Menu';
    var $displayField = 'title';
    //The Associations below have been created with all possible keys, those that are not needed can be removed

    var $belongsTo = array(
        'ParentMenu' => array(
            'className' => 'Menu',
            'foreignKey' => 'parent_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    var $hasMany = array(
        'ChildMenu' => array(
            'className' => 'Menu',
            'foreignKey' => 'parent_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => 'position',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );
    var $hasAndBelongsToMany = array(
        'UserRole' => array(
            'className' => 'UserRole',
            'joinTable' => 'user_role_menus',
            'foreignKey' => 'menu_id',
            'associationForeignKey' => 'user_role_id',
            'unique' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'finderQuery' => '',
            'deleteQuery' => '',
            'insertQuery' => ''
        )
    );

    public function getNavigationMenus($user) {
        $userRoleMenu = ClassRegistry::init('UserRoleMenu');
        
        $menu_ids = $userRoleMenu->find('list', array(
            'fields' => array('menu_id'),
            'conditions' => array('user_role_id' => $user['User']['user_role_id']),
            'recursive' => -1)
        );

        $menus = $this->find('all', array(
            'contain' => array(
                'ChildMenu' => array(
                    'conditions' => array(
                        'ChildMenu.id' => $menu_ids
                    )
                )
            ),
            'conditions' => array(
                'Menu.parent_id' => NULL,
                'Menu.id' => $menu_ids
            ),
            'order' => array('Menu.position'),
            'recursive' => 1)
        );

        return $menus;
    }

}

?>